Artificial Intelligence Nanodegree

Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Use a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 6: Write your Algorithm
  • Step 7: Test Your Algorithm

Step 0: Import Datasets

Import Dog Dataset

In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:

  • train_files, valid_files, test_files - numpy arrays containing file paths to images
  • train_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels
  • dog_names - list of string-valued dog breed names for translating labels
In [1]:
from sklearn.datasets import load_files       
from keras.utils import np_utils
import numpy as np
from glob import glob
import keras; print("Keras version: ", keras.__version__)
import tensorflow as tf; print("Tensorflow version: ", tf.__version__)

# define function to load train, test, and validation datasets
def load_dataset(path):
    data = load_files(path)
    dog_files = np.array(data['filenames'])
    dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
    return dog_files, dog_targets

# load train, test, and validation datasets
train_files, train_targets = load_dataset('/data/dog_images/train')
valid_files, valid_targets = load_dataset('/data/dog_images/valid')
test_files, test_targets = load_dataset('/data/dog_images/test')

# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob("/data/dog_images/train/*/"))]

# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
Keras version:  2.0.9
Tensorflow version:  1.3.0
There are 133 total dog categories.
There are 8351 total dog images.

There are 6680 training dog images.
There are 835 validation dog images.
There are 836 test dog images.

Import Human Dataset

In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.

In [2]:
import random
random.seed(8675309)

# load filenames in shuffled human dataset
human_files = np.array(glob("/data/lfw/*/*"))
random.shuffle(human_files)

# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
There are 13233 total human images.

Step 1: Detect Humans

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory.

In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [3]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[3])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [4]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer:

  • Percentage of the first 100 images in 'human_files' correcltly deteced as human faces: 100%
  • Percentage of the first 100 images in 'dog_files' correcltly deteced as human faces: 11%
In [5]:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Do NOT modify the code above this line.

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
human_face=0
dog_face=0

for face in human_files_short:
    if face_detector(face):
        human_face += 1

for face in dog_files_short:
    if face_detector(face):
        dog_face += 1

print("human faces counter: %d." % human_face)
print("dog faces counter: %d." % dog_face)
print("Percentage of detected human faces: %0.2f" % (human_face / len(human_files_short)))
print("Percentage of detected dog faces: %0.2f" % (dog_face / len(dog_files_short)))
human faces counter: 100.
dog faces counter: 11.
Percentage of detected human faces: 1.00
Percentage of detected dog faces: 0.11

Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?

Answer: I do not think that the necessity of comunicating to the user the need of a clear human face in the image is unreasonable. Nevertheless, we have enough data to train a CNN to detect humans from dogs. Besides, the application will be more friendly and easy to use if we avoid bothering the user with that kind of constrains. It might be also interesting to see if we could use another pretrained haarcascades detector (i.e. haarcascade_upperbody).

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on each of the datasets.

In [6]:
## (Optional) TODO: Report the performance of another  
## face detection algorithm on the LFW dataset
### Feel free to use as many code cells as needed.
from keras.preprocessing import image                  
from tqdm import tqdm

images = list()

#Collect the path images we will use to train our human face detector
for i in range(0, len(human_files) -3000):
    images.append(human_files[i])
    
# image number 1859 of the train_files dataset seem to have a problem
# I cannot load it and then convert it to an array -- Never knew why
for i in range(0, 1859):
    images.append(train_files[i])

for i in range(1860, len(train_files) - 3000):
    images.append(train_files[i])
    
# we generate labels vector
y_image_dataset = ([1]*(len(human_files) -3000) + [0]*(len(train_files) -3001))


def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)
In [7]:
image_dataset = paths_to_tensor(images)
print(image_dataset.shape)
print("finished")
100%|██████████| 13912/13912 [01:21<00:00, 169.96it/s]
(13912, 224, 224, 3)
finished
In [8]:
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dropout, Dense, Flatten, Activation
from keras.callbacks import ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from sklearn.model_selection import train_test_split
import numpy as np


# design of our CNN
human_detector = Sequential()
human_detector.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(224, 224, 3)))
human_detector.add(MaxPooling2D(pool_size=2))

#human_detector.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
#human_detector.add(MaxPooling2D(pool_size=2))
#human_detector.add(Dropout(0.1))

human_detector.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
human_detector.add(MaxPooling2D(pool_size=2))
human_detector.add(Dropout(0.1))

human_detector.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
human_detector.add(MaxPooling2D(pool_size=2))
human_detector.add(Dropout(0.3))

human_detector.add(Flatten())
human_detector.add(Dense(64, activation='relu'))
#human_detector.add(Dense(10, activation='relu'))
human_detector.add(Dropout(0.2))
human_detector.add(Dense(1, activation='sigmoid'))

human_detector.summary()


human_detector.compile(loss='binary_crossentropy', optimizer='adamax',
             metrics=['accuracy'])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 28, 28, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 50176)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                3211328   
_________________________________________________________________
dropout_3 (Dropout)          (None, 64)                0         
_________________________________________________________________
dense_2 (Dense)              (None, 1)                 65        
=================================================================
Total params: 3,221,937
Trainable params: 3,221,937
Non-trainable params: 0
_________________________________________________________________
In [9]:
# Create image data generator for image augmentation for both training and testing
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20,
                                  width_shift_range=0.2, height_shift_range=0.2, fill_mode='nearest',
                                  vertical_flip=True)

valid_datagen = ImageDataGenerator(rescale=1./255, rotation_range=20,
                                  width_shift_range=0.2, height_shift_range=0.2, fill_mode='nearest',
                                  vertical_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)
In [10]:
# set the size of a batch
batch_size = 32


# I divide our data set first in 70% training and 30 intermediate step
# I then divide the intermediate data set in to: 2/3 of this data set for validation and the
# remaining 1/3 for testing
X_train, X_inter, y_train_array, y_inter = train_test_split(image_dataset, y_image_dataset, test_size=0.3, shuffle=True,
                                                     random_state=81)
X_val, X_test, y_val_array, y_test_array = train_test_split(X_inter, y_inter, test_size=0.3, random_state=81)

y_train = np.array(y_train_array)
y_val = np.array(y_val_array)
y_test = np.array(y_test_array)

train_generator = train_datagen.flow(X_train, y_train, batch_size=batch_size,
                                     shuffle=True, seed=81)

valid_generator = valid_datagen.flow(X_val, y_val, batch_size=batch_size,
                                    shuffle=True, seed=81)

test_generator = test_datagen.flow(X_test, y_test, batch_size=batch_size,
                                  shuffle=True, seed=81)
In [11]:
from keras.callbacks import EarlyStopping
checkpointer = EarlyStopping(monitor='val_loss', patience = 12)
human_detector.fit_generator(train_generator, 
                    steps_per_epoch=(X_train.shape[0] // batch_size),
                    epochs=80,
                    verbose=1,
                    callbacks=[checkpointer],
                    validation_data=valid_generator,
                    validation_steps=(X_val.shape[0] // batch_size))


# load the weights that yielded the best validation accuracy
#human_detector.load_weights('human_face_detector.weights.best.hdf5')

# evaluate and print test accuracy
#score = human_detector.evaluate(X_test, y_test, verbose=0)
score = human_detector.evaluate_generator(test_generator, steps=(X_test.shape[0] // batch_size))
print('\n', 'Test accuracy:', score[1])
human_detector.save_weights("saved_models/human_detector_weights.h5")
print("weights of \"human_detector\" model saved")
Epoch 1/80
304/304 [==============================] - 114s 374ms/step - loss: 0.6436 - acc: 0.8043 - val_loss: 0.2845 - val_acc: 0.9080
Epoch 2/80
304/304 [==============================] - 102s 334ms/step - loss: 0.2579 - acc: 0.9023 - val_loss: 0.2458 - val_acc: 0.9172
Epoch 3/80
304/304 [==============================] - 102s 337ms/step - loss: 0.2109 - acc: 0.9258 - val_loss: 0.1920 - val_acc: 0.9375
Epoch 4/80
304/304 [==============================] - 101s 334ms/step - loss: 0.1911 - acc: 0.9321 - val_loss: 0.1982 - val_acc: 0.9334
Epoch 5/80
304/304 [==============================] - 101s 333ms/step - loss: 0.1937 - acc: 0.9328 - val_loss: 0.2741 - val_acc: 0.8647
Epoch 6/80
304/304 [==============================] - 102s 334ms/step - loss: 0.1667 - acc: 0.9440 - val_loss: 0.1224 - val_acc: 0.9619
Epoch 7/80
304/304 [==============================] - 101s 332ms/step - loss: 0.1533 - acc: 0.9505 - val_loss: 0.1277 - val_acc: 0.9591
Epoch 8/80
304/304 [==============================] - 101s 333ms/step - loss: 0.1523 - acc: 0.9495 - val_loss: 0.1546 - val_acc: 0.9471
Epoch 9/80
304/304 [==============================] - 102s 335ms/step - loss: 0.1334 - acc: 0.9571 - val_loss: 0.1074 - val_acc: 0.9653
Epoch 10/80
304/304 [==============================] - 102s 334ms/step - loss: 0.1309 - acc: 0.9597 - val_loss: 0.1163 - val_acc: 0.9619
Epoch 11/80
304/304 [==============================] - 102s 335ms/step - loss: 0.1207 - acc: 0.9624 - val_loss: 0.0933 - val_acc: 0.9677
Epoch 12/80
304/304 [==============================] - 102s 334ms/step - loss: 0.1016 - acc: 0.9681 - val_loss: 0.0785 - val_acc: 0.9746
Epoch 13/80
304/304 [==============================] - 102s 334ms/step - loss: 0.0878 - acc: 0.9710 - val_loss: 0.0821 - val_acc: 0.9708
Epoch 14/80
304/304 [==============================] - 102s 336ms/step - loss: 0.0986 - acc: 0.9658 - val_loss: 0.0886 - val_acc: 0.9657
Epoch 15/80
304/304 [==============================] - 102s 337ms/step - loss: 0.0949 - acc: 0.9680 - val_loss: 0.0690 - val_acc: 0.9766
Epoch 16/80
304/304 [==============================] - 102s 334ms/step - loss: 0.0942 - acc: 0.9679 - val_loss: 0.0818 - val_acc: 0.9694
Epoch 17/80
304/304 [==============================] - 101s 333ms/step - loss: 0.0901 - acc: 0.9699 - val_loss: 0.0719 - val_acc: 0.9770
Epoch 18/80
304/304 [==============================] - 102s 335ms/step - loss: 0.0813 - acc: 0.9743 - val_loss: 0.0616 - val_acc: 0.9815
Epoch 19/80
304/304 [==============================] - 101s 333ms/step - loss: 0.0840 - acc: 0.9734 - val_loss: 0.0581 - val_acc: 0.9811
Epoch 20/80
304/304 [==============================] - 101s 332ms/step - loss: 0.0817 - acc: 0.9704 - val_loss: 0.0841 - val_acc: 0.9674
Epoch 21/80
304/304 [==============================] - 101s 333ms/step - loss: 0.0697 - acc: 0.9774 - val_loss: 0.0578 - val_acc: 0.9804
Epoch 22/80
304/304 [==============================] - 101s 333ms/step - loss: 0.0757 - acc: 0.9749 - val_loss: 0.0626 - val_acc: 0.9780
Epoch 23/80
304/304 [==============================] - 101s 334ms/step - loss: 0.0692 - acc: 0.9775 - val_loss: 0.0517 - val_acc: 0.9821
Epoch 24/80
304/304 [==============================] - 100s 327ms/step - loss: 0.0684 - acc: 0.9776 - val_loss: 0.0521 - val_acc: 0.9845
Epoch 25/80
304/304 [==============================] - 100s 329ms/step - loss: 0.0645 - acc: 0.9794 - val_loss: 0.0598 - val_acc: 0.9784
Epoch 26/80
304/304 [==============================] - 99s 327ms/step - loss: 0.0667 - acc: 0.9765 - val_loss: 0.0657 - val_acc: 0.9749
Epoch 27/80
304/304 [==============================] - 99s 327ms/step - loss: 0.0601 - acc: 0.9811 - val_loss: 0.0503 - val_acc: 0.9811
Epoch 28/80
304/304 [==============================] - 100s 330ms/step - loss: 0.0566 - acc: 0.9819 - val_loss: 0.0470 - val_acc: 0.9852
Epoch 29/80
304/304 [==============================] - 99s 324ms/step - loss: 0.0593 - acc: 0.9823 - val_loss: 0.0618 - val_acc: 0.9794
Epoch 30/80
304/304 [==============================] - 99s 325ms/step - loss: 0.0556 - acc: 0.9821 - val_loss: 0.0380 - val_acc: 0.9876
Epoch 31/80
304/304 [==============================] - 100s 328ms/step - loss: 0.0557 - acc: 0.9814 - val_loss: 0.0448 - val_acc: 0.9863
Epoch 32/80
304/304 [==============================] - 100s 329ms/step - loss: 0.0587 - acc: 0.9822 - val_loss: 0.0350 - val_acc: 0.9890
Epoch 33/80
304/304 [==============================] - 100s 330ms/step - loss: 0.0544 - acc: 0.9821 - val_loss: 0.0374 - val_acc: 0.9866
Epoch 34/80
304/304 [==============================] - 100s 328ms/step - loss: 0.0574 - acc: 0.9814 - val_loss: 0.0653 - val_acc: 0.9784
Epoch 35/80
304/304 [==============================] - 100s 328ms/step - loss: 0.0594 - acc: 0.9825 - val_loss: 0.0569 - val_acc: 0.9818
Epoch 36/80
304/304 [==============================] - 100s 329ms/step - loss: 0.0518 - acc: 0.9837 - val_loss: 0.0506 - val_acc: 0.9842
Epoch 37/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0561 - acc: 0.9829 - val_loss: 0.0443 - val_acc: 0.9839
Epoch 38/80
304/304 [==============================] - 99s 325ms/step - loss: 0.0505 - acc: 0.9846 - val_loss: 0.0309 - val_acc: 0.9907
Epoch 39/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0468 - acc: 0.9855 - val_loss: 0.0443 - val_acc: 0.9845
Epoch 40/80
304/304 [==============================] - 99s 325ms/step - loss: 0.0455 - acc: 0.9857 - val_loss: 0.0394 - val_acc: 0.9839
Epoch 41/80
304/304 [==============================] - 99s 325ms/step - loss: 0.0487 - acc: 0.9853 - val_loss: 0.0509 - val_acc: 0.9845
Epoch 42/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0473 - acc: 0.9845 - val_loss: 0.0392 - val_acc: 0.9887
Epoch 43/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0496 - acc: 0.9843 - val_loss: 0.0334 - val_acc: 0.9911
Epoch 44/80
304/304 [==============================] - 99s 324ms/step - loss: 0.0459 - acc: 0.9838 - val_loss: 0.0374 - val_acc: 0.9856
Epoch 45/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0468 - acc: 0.9843 - val_loss: 0.0348 - val_acc: 0.9894
Epoch 46/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0467 - acc: 0.9834 - val_loss: 0.0358 - val_acc: 0.9883
Epoch 47/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0418 - acc: 0.9874 - val_loss: 0.0310 - val_acc: 0.9897
Epoch 48/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0415 - acc: 0.9867 - val_loss: 0.0359 - val_acc: 0.9887
Epoch 49/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0422 - acc: 0.9873 - val_loss: 0.0283 - val_acc: 0.9890
Epoch 50/80
304/304 [==============================] - 99s 324ms/step - loss: 0.0421 - acc: 0.9865 - val_loss: 0.0561 - val_acc: 0.9845
Epoch 51/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0405 - acc: 0.9865 - val_loss: 0.0490 - val_acc: 0.9832
Epoch 52/80
304/304 [==============================] - 99s 324ms/step - loss: 0.0419 - acc: 0.9862 - val_loss: 0.0321 - val_acc: 0.9904
Epoch 53/80
304/304 [==============================] - 99s 327ms/step - loss: 0.0358 - acc: 0.9881 - val_loss: 0.0284 - val_acc: 0.9918
Epoch 54/80
304/304 [==============================] - 99s 325ms/step - loss: 0.0355 - acc: 0.9892 - val_loss: 0.0261 - val_acc: 0.9900
Epoch 55/80
304/304 [==============================] - 98s 322ms/step - loss: 0.0379 - acc: 0.9872 - val_loss: 0.0260 - val_acc: 0.9897
Epoch 56/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0324 - acc: 0.9886 - val_loss: 0.0364 - val_acc: 0.9887
Epoch 57/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0357 - acc: 0.9883 - val_loss: 0.0260 - val_acc: 0.9907
Epoch 58/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0295 - acc: 0.9909 - val_loss: 0.0355 - val_acc: 0.9918
Epoch 59/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0366 - acc: 0.9891 - val_loss: 0.0246 - val_acc: 0.9924
Epoch 60/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0299 - acc: 0.9905 - val_loss: 0.0265 - val_acc: 0.9921
Epoch 61/80
304/304 [==============================] - 97s 318ms/step - loss: 0.0324 - acc: 0.9904 - val_loss: 0.0292 - val_acc: 0.9918
Epoch 62/80
304/304 [==============================] - 97s 318ms/step - loss: 0.0334 - acc: 0.9882 - val_loss: 0.0435 - val_acc: 0.9866
Epoch 63/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0366 - acc: 0.9885 - val_loss: 0.0311 - val_acc: 0.9880
Epoch 64/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0338 - acc: 0.9891 - val_loss: 0.0248 - val_acc: 0.9918
Epoch 65/80
304/304 [==============================] - 96s 316ms/step - loss: 0.0311 - acc: 0.9894 - val_loss: 0.0195 - val_acc: 0.9935
Epoch 66/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0314 - acc: 0.9899 - val_loss: 0.0286 - val_acc: 0.9900
Epoch 67/80
304/304 [==============================] - 97s 318ms/step - loss: 0.0342 - acc: 0.9894 - val_loss: 0.0268 - val_acc: 0.9894
Epoch 68/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0311 - acc: 0.9902 - val_loss: 0.0163 - val_acc: 0.9938
Epoch 69/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0311 - acc: 0.9907 - val_loss: 0.0291 - val_acc: 0.9907
Epoch 70/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0298 - acc: 0.9896 - val_loss: 0.0414 - val_acc: 0.9845
Epoch 71/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0326 - acc: 0.9897 - val_loss: 0.0272 - val_acc: 0.9921
Epoch 72/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0307 - acc: 0.9903 - val_loss: 0.0315 - val_acc: 0.9883
Epoch 73/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0325 - acc: 0.9900 - val_loss: 0.0296 - val_acc: 0.9883
Epoch 74/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0301 - acc: 0.9906 - val_loss: 0.0257 - val_acc: 0.9897
Epoch 75/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0299 - acc: 0.9907 - val_loss: 0.0172 - val_acc: 0.9935
Epoch 76/80
304/304 [==============================] - 97s 321ms/step - loss: 0.0274 - acc: 0.9907 - val_loss: 0.0445 - val_acc: 0.9859
Epoch 77/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0280 - acc: 0.9911 - val_loss: 0.0222 - val_acc: 0.9931
Epoch 78/80
304/304 [==============================] - 97s 320ms/step - loss: 0.0273 - acc: 0.9914 - val_loss: 0.0301 - val_acc: 0.9883
Epoch 79/80
304/304 [==============================] - 98s 321ms/step - loss: 0.0266 - acc: 0.9920 - val_loss: 0.0305 - val_acc: 0.9894
Epoch 80/80
304/304 [==============================] - 97s 319ms/step - loss: 0.0266 - acc: 0.9914 - val_loss: 0.0197 - val_acc: 0.9931

 Test accuracy: 0.992788461538
weights of "human_detector" model saved
In [11]:
human_detector.load_weights("saved_models/human_detector_weights.h5")
human_files_short_loaded = paths_to_tensor(human_files_short)
dog_files_short_loaded = paths_to_tensor(dog_files_short)
print("Lengths humans: ", len(human_files_short_loaded))
print("Lengths dogs: ", len(dog_files_short_loaded))

test_human_generator = test_datagen.flow(human_files_short_loaded, batch_size=25)
final_human_predictions = human_detector.predict_generator(test_human_generator, steps=(human_files_short_loaded.shape[0] // 25),
                                       verbose=1)
human_faces = 0
for i in final_human_predictions:
    human_faces  += int(i > 0.60)
        #human_faces += 1

test_dog_generator = test_datagen.flow(dog_files_short_loaded, batch_size=25)
final_dog_predictions = human_detector.predict_generator(test_dog_generator, steps=(dog_files_short_loaded.shape[0] // 25),
                                       verbose=1)
dog_faces = 0
for i in final_dog_predictions:
    dog_faces  += int(i > 0.60)


print("human faces counter: %d." % human_faces)
print("dog faces counter: %d." % dog_faces)
print("Percentage of detected human faces: %0.2f" % (human_faces / len(human_files_short_loaded)))
print("Percentage of detected dog faces: %0.2f" % (dog_faces / len(dog_files_short_loaded)))
100%|██████████| 100/100 [00:02<00:00, 37.95it/s]
100%|██████████| 100/100 [00:02<00:00, 43.29it/s]
Lengths humans:  100
Lengths dogs:  100
4/4 [==============================] - 4s 921ms/step
4/4 [==============================] - 0s 33ms/step
human faces counter: 100.
dog faces counter: 0.
Percentage of detected human faces: 1.00
Percentage of detected dog faces: 0.00

Step 2: Detect Dogs

In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.

In [12]:
from keras.applications.resnet50 import ResNet50

# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering_tf_kernels.h5
102858752/102853048 [==============================] - 3s 0us/step

Pre-process the Data

When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape

$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$

where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.

The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape

$$ (1, 224, 224, 3). $$

The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape

$$ (\text{nb_samples}, 224, 224, 3). $$

Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!

In [13]:
from keras.preprocessing import image                  
from tqdm import tqdm

def path_to_tensor(img_path):
    # loads RGB image as PIL.Image.Image type
    img = image.load_img(img_path, target_size=(224, 224))
    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
    x = image.img_to_array(img)
    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
    return np.expand_dims(x, axis=0)

def paths_to_tensor(img_paths):
    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
    return np.vstack(list_of_tensors)

Making Predictions with ResNet-50

Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.

Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.

By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.

In [14]:
from keras.applications.resnet50 import preprocess_input, decode_predictions

def ResNet50_predict_labels(img_path):
    # returns prediction vector for image located at img_path
    img = preprocess_input(path_to_tensor(img_path))
    return np.argmax(ResNet50_model.predict(img))

Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).

We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [15]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    prediction = ResNet50_predict_labels(img_path)
    return ((prediction <= 268) & (prediction >= 151)) 

(IMPLEMENTATION) Assess the Dog Detector

Question 3: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer:

Percentage of the image in 'human_files_short': 0%

Percentage of the image in 'dog_files_short': 100%

In [16]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

human_faces = 0
for i in human_files_short:
    human_faces  += int(dog_detector(i))
        #human_faces += 1

dog_faces = 0
for i in dog_files_short:
    dog_faces  += int(dog_detector(i))


print("human faces counter: %d." % human_faces)
print("dog faces counter: %d." % dog_faces)
print("Percentage of detected human faces: %0.2f" % (human_faces / len(human_files_short)))
print("Percentage of detected dog faces: %0.2f" % (dog_faces / len(dog_files_short)))
human faces counter: 0.
dog faces counter: 100.
Percentage of detected human faces: 0.00
Percentage of detected dog faces: 1.00

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

Pre-process the Data

We rescale the images by dividing every pixel in every image by 255.

In [17]:
from PIL import ImageFile                            
ImageFile.LOAD_TRUNCATED_IMAGES = True                 

# pre-process the data for Keras
train_tensors = paths_to_tensor(train_files).astype('float32')/255
valid_tensors = paths_to_tensor(valid_files).astype('float32')/255
test_tensors = paths_to_tensor(test_files).astype('float32')/255
100%|██████████| 6680/6680 [02:08<00:00, 52.01it/s]
100%|██████████| 835/835 [00:10<00:00, 82.06it/s] 
100%|██████████| 836/836 [00:10<00:00, 82.26it/s] 

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    model.summary()

We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:

Sample CNN

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.

Answer:

I decided to reused the CNN that I designed to recognize human faces and replacing only the sigmoid output for a FCN for 133 using softmax activation. I ran 80 epochs. I found out that there were no more improvement in the validation accuracy after the 9th epoch and I got an accuracy of 5.3828%.

I then modified my CNN,removing the last Dropout before the Flatten layer and all the layers that followed. Instead I used a GlobalAveragePooling2D layer followed by a Dense layer with 133 nodes and softmax activation.

With my first CNN designed I had already gotten more than the 1%, nevertheless I wanted to compare the accuracy and performance of my first design against a modified design using GlobalAveragePooling2D. With this last (modified) design I obtained an accuracy of 6.2201%. Nevertheless, with the new design it took much more epochs to reach a similar accuracy.

In [18]:
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential

model = Sequential()

### TODO: Define your architecture.
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=2))

model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.1))

model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
#model.add(Dropout(0.3))                                 # USING THESE lines Iget an accuracy of 5.3828%
model.add(GlobalAveragePooling2D())   # using these lines I get an accuracy of 9.3301%

#model.add(Flatten())                                    # USING THESE lines Iget an accuracy of 5.9809%
#model.add(Dense(64, activation='relu'))                 # USING THESE lines Iget an accuracy of 5.9809%
#model.add(Dropout(0.2))                                 # USING THESE lines Iget an accuracy of 5.9809%
model.add(Dense(133, activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_4 (Conv2D)            (None, 224, 224, 16)      208       
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 112, 112, 16)      0         
_________________________________________________________________
conv2d_5 (Conv2D)            (None, 112, 112, 32)      2080      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 56, 56, 32)        0         
_________________________________________________________________
dropout_4 (Dropout)          (None, 56, 56, 32)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 56, 56, 64)        8256      
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 28, 28, 64)        0         
_________________________________________________________________
global_average_pooling2d_1 ( (None, 64)                0         
_________________________________________________________________
dense_3 (Dense)              (None, 133)               8645      
=================================================================
Total params: 19,189
Trainable params: 19,189
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [19]:
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [15]:
from keras.callbacks import ModelCheckpoint  

### TODO: specify the number of epochs that you would like to use to train the model.

epochs = 80

### Do NOT modify the code below this line.

checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', 
                               verbose=1, save_best_only=True)

model.fit(train_tensors, train_targets, 
          validation_data=(valid_tensors, valid_targets),
          epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.8838 - acc: 0.0074Epoch 00001: val_loss improved from inf to 4.87093, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.8838 - acc: 0.0073 - val_loss: 4.8709 - val_acc: 0.0108
Epoch 2/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.8696 - acc: 0.0098Epoch 00002: val_loss improved from 4.87093 to 4.86298, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.8694 - acc: 0.0099 - val_loss: 4.8630 - val_acc: 0.0108
Epoch 3/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.8422 - acc: 0.0143Epoch 00003: val_loss improved from 4.86298 to 4.82890, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.8423 - acc: 0.0142 - val_loss: 4.8289 - val_acc: 0.0180
Epoch 4/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.8002 - acc: 0.0167Epoch 00004: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7998 - acc: 0.0166 - val_loss: 4.8545 - val_acc: 0.0204
Epoch 5/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.7677 - acc: 0.0203Epoch 00005: val_loss improved from 4.82890 to 4.77761, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7675 - acc: 0.0205 - val_loss: 4.7776 - val_acc: 0.0192
Epoch 6/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.7374 - acc: 0.0216Epoch 00006: val_loss improved from 4.77761 to 4.75309, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7376 - acc: 0.0216 - val_loss: 4.7531 - val_acc: 0.0299
Epoch 7/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.7112 - acc: 0.0272Epoch 00007: val_loss improved from 4.75309 to 4.73411, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.7114 - acc: 0.0271 - val_loss: 4.7341 - val_acc: 0.0251
Epoch 8/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.6893 - acc: 0.0290Epoch 00008: val_loss improved from 4.73411 to 4.71867, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6896 - acc: 0.0289 - val_loss: 4.7187 - val_acc: 0.0251
Epoch 9/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.6662 - acc: 0.0324Epoch 00009: val_loss improved from 4.71867 to 4.71439, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6664 - acc: 0.0323 - val_loss: 4.7144 - val_acc: 0.0263
Epoch 10/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.6436 - acc: 0.0336Epoch 00010: val_loss improved from 4.71439 to 4.70311, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6424 - acc: 0.0340 - val_loss: 4.7031 - val_acc: 0.0347
Epoch 11/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.6190 - acc: 0.0330Epoch 00011: val_loss improved from 4.70311 to 4.66488, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.6189 - acc: 0.0329 - val_loss: 4.6649 - val_acc: 0.0431
Epoch 12/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.5936 - acc: 0.0417Epoch 00012: val_loss improved from 4.66488 to 4.66392, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5947 - acc: 0.0416 - val_loss: 4.6639 - val_acc: 0.0431
Epoch 13/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.5691 - acc: 0.0419Epoch 00013: val_loss improved from 4.66392 to 4.64065, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.5701 - acc: 0.0421 - val_loss: 4.6407 - val_acc: 0.0407
Epoch 14/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.5514 - acc: 0.0440Epoch 00014: val_loss improved from 4.64065 to 4.61846, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.5508 - acc: 0.0442 - val_loss: 4.6185 - val_acc: 0.0371
Epoch 15/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.5289 - acc: 0.0446Epoch 00015: val_loss improved from 4.61846 to 4.60045, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5288 - acc: 0.0446 - val_loss: 4.6004 - val_acc: 0.0371
Epoch 16/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.5095 - acc: 0.0467Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.5107 - acc: 0.0469 - val_loss: 4.6039 - val_acc: 0.0431
Epoch 17/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.4860 - acc: 0.0498Epoch 00017: val_loss improved from 4.60045 to 4.57255, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4862 - acc: 0.0501 - val_loss: 4.5725 - val_acc: 0.0431
Epoch 18/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.4679 - acc: 0.0547Epoch 00018: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4672 - acc: 0.0548 - val_loss: 4.6095 - val_acc: 0.0347
Epoch 19/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.4416 - acc: 0.0550Epoch 00019: val_loss improved from 4.57255 to 4.55453, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4419 - acc: 0.0548 - val_loss: 4.5545 - val_acc: 0.0407
Epoch 20/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.4312 - acc: 0.0577Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4302 - acc: 0.0581 - val_loss: 4.6249 - val_acc: 0.0407
Epoch 21/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.4132 - acc: 0.0616Epoch 00021: val_loss improved from 4.55453 to 4.51238, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.4134 - acc: 0.0615 - val_loss: 4.5124 - val_acc: 0.0467
Epoch 22/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3936 - acc: 0.0631Epoch 00022: val_loss improved from 4.51238 to 4.50875, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3936 - acc: 0.0632 - val_loss: 4.5087 - val_acc: 0.0455
Epoch 23/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3751 - acc: 0.0631Epoch 00023: val_loss improved from 4.50875 to 4.50605, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3740 - acc: 0.0632 - val_loss: 4.5060 - val_acc: 0.0455
Epoch 24/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3573 - acc: 0.0668Epoch 00024: val_loss improved from 4.50605 to 4.47202, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3573 - acc: 0.0668 - val_loss: 4.4720 - val_acc: 0.0455
Epoch 25/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3376 - acc: 0.0692Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3371 - acc: 0.0692 - val_loss: 4.4997 - val_acc: 0.0491
Epoch 26/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3162 - acc: 0.0686Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 21s 3ms/step - loss: 4.3161 - acc: 0.0684 - val_loss: 4.4848 - val_acc: 0.0527
Epoch 27/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.3104 - acc: 0.0655Epoch 00027: val_loss improved from 4.47202 to 4.45369, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.3097 - acc: 0.0656 - val_loss: 4.4537 - val_acc: 0.0563
Epoch 28/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2898 - acc: 0.0704Epoch 00028: val_loss improved from 4.45369 to 4.42182, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2895 - acc: 0.0704 - val_loss: 4.4218 - val_acc: 0.0611
Epoch 29/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2733 - acc: 0.0743Epoch 00029: val_loss improved from 4.42182 to 4.39142, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2731 - acc: 0.0744 - val_loss: 4.3914 - val_acc: 0.0695
Epoch 30/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2519 - acc: 0.0751Epoch 00030: val_loss improved from 4.39142 to 4.38769, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2515 - acc: 0.0753 - val_loss: 4.3877 - val_acc: 0.0587
Epoch 31/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2367 - acc: 0.0757Epoch 00031: val_loss improved from 4.38769 to 4.38668, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2373 - acc: 0.0756 - val_loss: 4.3867 - val_acc: 0.0599
Epoch 32/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2260 - acc: 0.0760Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2249 - acc: 0.0763 - val_loss: 4.4309 - val_acc: 0.0647
Epoch 33/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.2065 - acc: 0.0841Epoch 00033: val_loss improved from 4.38668 to 4.36964, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.2059 - acc: 0.0840 - val_loss: 4.3696 - val_acc: 0.0647
Epoch 34/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1911 - acc: 0.0812Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 21s 3ms/step - loss: 4.1902 - acc: 0.0813 - val_loss: 4.4161 - val_acc: 0.0611
Epoch 35/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1808 - acc: 0.0845Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1817 - acc: 0.0847 - val_loss: 4.3876 - val_acc: 0.0671
Epoch 36/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1688 - acc: 0.0817Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 21s 3ms/step - loss: 4.1683 - acc: 0.0817 - val_loss: 4.3761 - val_acc: 0.0587
Epoch 37/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1555 - acc: 0.0901Epoch 00037: val_loss improved from 4.36964 to 4.34423, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.1548 - acc: 0.0906 - val_loss: 4.3442 - val_acc: 0.0671
Epoch 38/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1418 - acc: 0.0874Epoch 00038: val_loss improved from 4.34423 to 4.30378, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.1429 - acc: 0.0873 - val_loss: 4.3038 - val_acc: 0.0731
Epoch 39/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1296 - acc: 0.0895Epoch 00039: val_loss improved from 4.30378 to 4.30088, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1297 - acc: 0.0895 - val_loss: 4.3009 - val_acc: 0.0766
Epoch 40/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1226 - acc: 0.0917Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1215 - acc: 0.0919 - val_loss: 4.4087 - val_acc: 0.0719
Epoch 41/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.1026 - acc: 0.0928Epoch 00041: val_loss improved from 4.30088 to 4.29304, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.1042 - acc: 0.0925 - val_loss: 4.2930 - val_acc: 0.0743
Epoch 42/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0962 - acc: 0.0935Epoch 00042: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0965 - acc: 0.0933 - val_loss: 4.3259 - val_acc: 0.0731
Epoch 43/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0864 - acc: 0.0935Epoch 00043: val_loss improved from 4.29304 to 4.27975, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0880 - acc: 0.0933 - val_loss: 4.2798 - val_acc: 0.0778
Epoch 44/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0752 - acc: 0.0958Epoch 00044: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0735 - acc: 0.0961 - val_loss: 4.3596 - val_acc: 0.0671
Epoch 45/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0592 - acc: 0.0967Epoch 00045: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0597 - acc: 0.0969 - val_loss: 4.3190 - val_acc: 0.0719
Epoch 46/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0549 - acc: 0.0991Epoch 00046: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0540 - acc: 0.0996 - val_loss: 4.2806 - val_acc: 0.0719
Epoch 47/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0433 - acc: 0.1020Epoch 00047: val_loss improved from 4.27975 to 4.26805, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0436 - acc: 0.1019 - val_loss: 4.2680 - val_acc: 0.0743
Epoch 48/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0277 - acc: 0.1021Epoch 00048: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0279 - acc: 0.1019 - val_loss: 4.2854 - val_acc: 0.0731
Epoch 49/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0218 - acc: 0.1002Epoch 00049: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0224 - acc: 0.1003 - val_loss: 4.2806 - val_acc: 0.0802
Epoch 50/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0162 - acc: 0.1033Epoch 00050: val_loss improved from 4.26805 to 4.25799, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 4.0155 - acc: 0.1034 - val_loss: 4.2580 - val_acc: 0.0886
Epoch 51/80
6660/6680 [============================>.] - ETA: 0s - loss: 4.0048 - acc: 0.1036Epoch 00051: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0058 - acc: 0.1034 - val_loss: 4.2674 - val_acc: 0.0862
Epoch 52/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9995 - acc: 0.1065Epoch 00052: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 4.0001 - acc: 0.1063 - val_loss: 4.2655 - val_acc: 0.0802
Epoch 53/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9898 - acc: 0.1068Epoch 00053: val_loss improved from 4.25799 to 4.25584, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9890 - acc: 0.1069 - val_loss: 4.2558 - val_acc: 0.0766
Epoch 54/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9729 - acc: 0.1075Epoch 00054: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9737 - acc: 0.1075 - val_loss: 4.2686 - val_acc: 0.0754
Epoch 55/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9737 - acc: 0.1114Epoch 00055: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9730 - acc: 0.1117 - val_loss: 4.2607 - val_acc: 0.0826
Epoch 56/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9604 - acc: 0.1128Epoch 00056: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9619 - acc: 0.1126 - val_loss: 4.2567 - val_acc: 0.0838
Epoch 57/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9470 - acc: 0.1132Epoch 00057: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9466 - acc: 0.1130 - val_loss: 4.2608 - val_acc: 0.0862
Epoch 58/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9415 - acc: 0.1159Epoch 00058: val_loss improved from 4.25584 to 4.20232, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9409 - acc: 0.1165 - val_loss: 4.2023 - val_acc: 0.0910
Epoch 59/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9358 - acc: 0.1173Epoch 00059: val_loss improved from 4.20232 to 4.19506, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9353 - acc: 0.1174 - val_loss: 4.1951 - val_acc: 0.0850
Epoch 60/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9188 - acc: 0.1153Epoch 00060: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9210 - acc: 0.1150 - val_loss: 4.2064 - val_acc: 0.0862
Epoch 61/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9178 - acc: 0.1221Epoch 00061: val_loss improved from 4.19506 to 4.17196, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9162 - acc: 0.1222 - val_loss: 4.1720 - val_acc: 0.0874
Epoch 62/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.9031 - acc: 0.1177Epoch 00062: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.9028 - acc: 0.1177 - val_loss: 4.1790 - val_acc: 0.0826
Epoch 63/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8989 - acc: 0.1182Epoch 00063: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8986 - acc: 0.1180 - val_loss: 4.1940 - val_acc: 0.0850
Epoch 64/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8897 - acc: 0.1192Epoch 00064: val_loss did not improve
6680/6680 [==============================] - 21s 3ms/step - loss: 3.8887 - acc: 0.1193 - val_loss: 4.2044 - val_acc: 0.0910
Epoch 65/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8795 - acc: 0.1200Epoch 00065: val_loss did not improve
6680/6680 [==============================] - 21s 3ms/step - loss: 3.8794 - acc: 0.1201 - val_loss: 4.2100 - val_acc: 0.0814
Epoch 66/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8700 - acc: 0.1224Epoch 00066: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8704 - acc: 0.1226 - val_loss: 4.1912 - val_acc: 0.0802
Epoch 67/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8646 - acc: 0.1263Epoch 00067: val_loss improved from 4.17196 to 4.15635, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8655 - acc: 0.1262 - val_loss: 4.1564 - val_acc: 0.0910
Epoch 68/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8555 - acc: 0.1251Epoch 00068: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8547 - acc: 0.1253 - val_loss: 4.1636 - val_acc: 0.0934
Epoch 69/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8460 - acc: 0.1288Epoch 00069: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8466 - acc: 0.1290 - val_loss: 4.2621 - val_acc: 0.0790
Epoch 70/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8411 - acc: 0.1338Epoch 00070: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8404 - acc: 0.1335 - val_loss: 4.1929 - val_acc: 0.0898
Epoch 71/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8365 - acc: 0.1272Epoch 00071: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8355 - acc: 0.1272 - val_loss: 4.1742 - val_acc: 0.0898
Epoch 72/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8209 - acc: 0.1309Epoch 00072: val_loss improved from 4.15635 to 4.15277, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8204 - acc: 0.1310 - val_loss: 4.1528 - val_acc: 0.0898
Epoch 73/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8108 - acc: 0.1309Epoch 00073: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8125 - acc: 0.1308 - val_loss: 4.1735 - val_acc: 0.0946
Epoch 74/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.8040 - acc: 0.1368Epoch 00074: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.8026 - acc: 0.1371 - val_loss: 4.1685 - val_acc: 0.0898
Epoch 75/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7987 - acc: 0.1357Epoch 00075: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.7991 - acc: 0.1356 - val_loss: 4.2007 - val_acc: 0.0874
Epoch 76/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7870 - acc: 0.1347Epoch 00076: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.7877 - acc: 0.1344 - val_loss: 4.2039 - val_acc: 0.0778
Epoch 77/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7797 - acc: 0.1444Epoch 00077: val_loss did not improve
6680/6680 [==============================] - 22s 3ms/step - loss: 3.7804 - acc: 0.1442 - val_loss: 4.1789 - val_acc: 0.0850
Epoch 78/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7683 - acc: 0.1404Epoch 00078: val_loss improved from 4.15277 to 4.13281, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.7689 - acc: 0.1401 - val_loss: 4.1328 - val_acc: 0.0886
Epoch 79/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7616 - acc: 0.1419Epoch 00079: val_loss improved from 4.13281 to 4.12293, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 22s 3ms/step - loss: 3.7600 - acc: 0.1418 - val_loss: 4.1229 - val_acc: 0.0910
Epoch 80/80
6660/6680 [============================>.] - ETA: 0s - loss: 3.7470 - acc: 0.1399Epoch 00080: val_loss improved from 4.12293 to 4.10018, saving model to saved_models/weights.best.from_scratch.hdf5
6680/6680 [==============================] - 21s 3ms/step - loss: 3.7473 - acc: 0.1401 - val_loss: 4.1002 - val_acc: 0.0994
Out[15]:
<keras.callbacks.History at 0x7f86c2ec5128>

Load the Model with the Best Validation Loss

In [20]:
model.load_weights('saved_models/weights.best.from_scratch.hdf5')

Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.

In [21]:
# get index of predicted dog breed for each image in test set
dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]

# report test accuracy
test_accuracy = 100*np.sum(np.array(dog_breed_predictions)==np.argmax(test_targets, axis=1))/len(dog_breed_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 9.3301%

Step 4: Use a CNN to Classify Dog Breeds

To reduce training time without sacrificing accuracy, we show you how to train a CNN using transfer learning. In the following step, you will get a chance to use transfer learning to train your own CNN.

Obtain Bottleneck Features

In [22]:
bottleneck_features = np.load('/data/bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']

Model Architecture

The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.

In [23]:
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))

VGG16_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_2 ( (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 133)               68229     
=================================================================
Total params: 68,229
Trainable params: 68,229
Non-trainable params: 0
_________________________________________________________________

Compile the Model

In [24]:
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

Train the Model

In [7]:
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5', 
                               verbose=1, save_best_only=True)

VGG16_model.fit(train_VGG16, train_targets, 
          validation_data=(valid_VGG16, valid_targets),
          epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/20
6540/6680 [============================>.] - ETA: 0s - loss: 12.2352 - acc: 0.1278Epoch 00001: val_loss improved from inf to 10.71527, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 364us/step - loss: 12.2084 - acc: 0.1304 - val_loss: 10.7153 - val_acc: 0.2383
Epoch 2/20
6500/6680 [============================>.] - ETA: 0s - loss: 10.2611 - acc: 0.2869Epoch 00002: val_loss improved from 10.71527 to 10.08520, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 255us/step - loss: 10.2473 - acc: 0.2876 - val_loss: 10.0852 - val_acc: 0.3042
Epoch 3/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.7856 - acc: 0.3424Epoch 00003: val_loss improved from 10.08520 to 9.84769, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 9.7788 - acc: 0.3427 - val_loss: 9.8477 - val_acc: 0.3186
Epoch 4/20
6620/6680 [============================>.] - ETA: 0s - loss: 9.5153 - acc: 0.3722Epoch 00004: val_loss improved from 9.84769 to 9.64455, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 9.5104 - acc: 0.3726 - val_loss: 9.6445 - val_acc: 0.3545
Epoch 5/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.4139 - acc: 0.3905Epoch 00005: val_loss improved from 9.64455 to 9.63568, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 9.4098 - acc: 0.3909 - val_loss: 9.6357 - val_acc: 0.3641
Epoch 6/20
6600/6680 [============================>.] - ETA: 0s - loss: 9.2699 - acc: 0.4047Epoch 00006: val_loss improved from 9.63568 to 9.50556, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 9.2750 - acc: 0.4042 - val_loss: 9.5056 - val_acc: 0.3629
Epoch 7/20
6660/6680 [============================>.] - ETA: 0s - loss: 9.0811 - acc: 0.4135Epoch 00007: val_loss improved from 9.50556 to 9.39584, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 9.0829 - acc: 0.4135 - val_loss: 9.3958 - val_acc: 0.3605
Epoch 8/20
6580/6680 [============================>.] - ETA: 0s - loss: 8.9496 - acc: 0.4266Epoch 00008: val_loss improved from 9.39584 to 9.30037, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 247us/step - loss: 8.9381 - acc: 0.4272 - val_loss: 9.3004 - val_acc: 0.3737
Epoch 9/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.8763 - acc: 0.4390Epoch 00009: val_loss improved from 9.30037 to 9.28208, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 244us/step - loss: 8.8764 - acc: 0.4389 - val_loss: 9.2821 - val_acc: 0.3832
Epoch 10/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.6913 - acc: 0.4466Epoch 00010: val_loss improved from 9.28208 to 8.98929, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 8.6726 - acc: 0.4478 - val_loss: 8.9893 - val_acc: 0.3856
Epoch 11/20
6600/6680 [============================>.] - ETA: 0s - loss: 8.4582 - acc: 0.4580Epoch 00011: val_loss improved from 8.98929 to 8.89165, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 8.4648 - acc: 0.4575 - val_loss: 8.8917 - val_acc: 0.4000
Epoch 12/20
6660/6680 [============================>.] - ETA: 0s - loss: 8.3238 - acc: 0.4716Epoch 00012: val_loss improved from 8.89165 to 8.75216, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 244us/step - loss: 8.3313 - acc: 0.4711 - val_loss: 8.7522 - val_acc: 0.4012
Epoch 13/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.2946 - acc: 0.4770Epoch 00013: val_loss did not improve
6680/6680 [==============================] - 2s 244us/step - loss: 8.2844 - acc: 0.4775 - val_loss: 8.7998 - val_acc: 0.4036
Epoch 14/20
6560/6680 [============================>.] - ETA: 0s - loss: 8.2250 - acc: 0.4817Epoch 00014: val_loss improved from 8.75216 to 8.65986, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 8.2367 - acc: 0.4810 - val_loss: 8.6599 - val_acc: 0.4072
Epoch 15/20
6620/6680 [============================>.] - ETA: 0s - loss: 8.2002 - acc: 0.4841Epoch 00015: val_loss did not improve
6680/6680 [==============================] - 2s 243us/step - loss: 8.1939 - acc: 0.4843 - val_loss: 8.6759 - val_acc: 0.4048
Epoch 16/20
6480/6680 [============================>.] - ETA: 0s - loss: 8.0894 - acc: 0.4856Epoch 00016: val_loss improved from 8.65986 to 8.48092, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 8.0787 - acc: 0.4865 - val_loss: 8.4809 - val_acc: 0.4240
Epoch 17/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.9844 - acc: 0.4956Epoch 00017: val_loss improved from 8.48092 to 8.42318, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 7.9871 - acc: 0.4955 - val_loss: 8.4232 - val_acc: 0.4180
Epoch 18/20
6640/6680 [============================>.] - ETA: 0s - loss: 7.8919 - acc: 0.4997Epoch 00018: val_loss improved from 8.42318 to 8.41158, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 7.8856 - acc: 0.5001 - val_loss: 8.4116 - val_acc: 0.4299
Epoch 19/20
6620/6680 [============================>.] - ETA: 0s - loss: 7.7534 - acc: 0.5073Epoch 00019: val_loss improved from 8.41158 to 8.20784, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 246us/step - loss: 7.7389 - acc: 0.5079 - val_loss: 8.2078 - val_acc: 0.4299
Epoch 20/20
6460/6680 [============================>.] - ETA: 0s - loss: 7.5317 - acc: 0.5183Epoch 00020: val_loss improved from 8.20784 to 8.08200, saving model to saved_models/weights.best.VGG16.hdf5
6680/6680 [==============================] - 2s 245us/step - loss: 7.5091 - acc: 0.5199 - val_loss: 8.0820 - val_acc: 0.4407
Out[7]:
<keras.callbacks.History at 0x7f487d2d6f98>

Load the Model with the Best Validation Loss

In [25]:
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')

Test the Model

Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.

In [26]:
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]

# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Test accuracy: 44.2584%

Predict Dog Breed with the Model

In [27]:
from extract_bottleneck_features import *

def VGG16_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = VGG16_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

Step 5: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras. These are already in the workspace, at /data/bottleneck_features. If you wish to download them on a different machine, they can be found at:

The files are encoded as such:

Dog{network}Data.npz

where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception.

The above architectures are downloaded and stored for you in the /data/bottleneck_features/ folder.

This means the following will be in the /data/bottleneck_features/ folder:

DogVGG19Data.npz DogResnet50Data.npz DogInceptionV3Data.npz DogXceptionData.npz

(IMPLEMENTATION) Obtain Bottleneck Features

In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:

bottleneck_features = np.load('/data/bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
In [28]:
### TODO: Obtain bottleneck features from another pre-trained CNN.
bottleneck_features_Xception = np.load('/data/bottleneck_features/DogXceptionData.npz')
train_Xception = bottleneck_features_Xception['train']
valid_Xception = bottleneck_features_Xception['valid']
test_Xception = bottleneck_features_Xception['test']

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line:

    <your model's name>.summary()

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

First I tried to modify the given code by adding more layers. I actually tried to reuse the architecture I used for the person's face detector, but the accuracy I could get was really low, so I ended up using the architecture shown below. Starting from there as an (new) initial point, I tried to get a higher accuracy by playing around a bit with different optimizers or adding more FCN layers after the Global Average Pooling layer. However the accuracy was either not improving or in some cases it was actually decreasing. I also tried to used the architecture shown below, to make some predictions (once it was trained) which I would then save to use them as input to another FCN architecture (you can see this second architecture below, with the name Xception_modelz), to try to increase the accuracy, but then again, the accuracy was either not increasing or it was -in some cases- decreasing.

Finally I adjusted the batch_size in what I believe, gives me the best possible accuracy.

In [29]:
### TODO: Define your architecture.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint

Xception_model = Sequential()
Xception_model.add(GlobalAveragePooling2D(input_shape=train_Xception.shape[1:]))
#Xception_model.add(Dense(133, activation='tanh'))
#Xception_model.add(Dropout(0.1))
Xception_model.add(Dense(133, activation='softmax'))

Xception_model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
global_average_pooling2d_3 ( (None, 2048)              0         
_________________________________________________________________
dense_5 (Dense)              (None, 133)               272517    
=================================================================
Total params: 272,517
Trainable params: 272,517
Non-trainable params: 0
_________________________________________________________________

(IMPLEMENTATION) Compile the Model

In [30]:
### TODO: Compile the model.
Xception_model.compile(loss='categorical_crossentropy', optimizer='adamax', metrics=['accuracy'])

(IMPLEMENTATION) Train the Model

Train your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.

You are welcome to augment the training data, but this is not a requirement.

In [10]:
### TODO: Train the model.
#checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
#                               verbose=1, save_best_only=True)
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.Xception.hdf5', 
                               verbose=1, save_best_only=True)

Xception_model.fit(train_Xception, train_targets, 
          validation_data=(valid_Xception, valid_targets),
          epochs=40, batch_size=150, callbacks=[checkpointer], verbose=1)
Train on 6680 samples, validate on 835 samples
Epoch 1/40
6450/6680 [===========================>..] - ETA: 0s - loss: 2.0854 - acc: 0.6042Epoch 00001: val_loss improved from inf to 0.84316, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 4s 559us/step - loss: 2.0445 - acc: 0.6099 - val_loss: 0.8432 - val_acc: 0.8072
Epoch 2/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.6206 - acc: 0.8583Epoch 00002: val_loss improved from 0.84316 to 0.62751, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 0.6201 - acc: 0.8588 - val_loss: 0.6275 - val_acc: 0.8359
Epoch 3/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.4695 - acc: 0.8910Epoch 00003: val_loss improved from 0.62751 to 0.56050, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 274us/step - loss: 0.4691 - acc: 0.8913 - val_loss: 0.5605 - val_acc: 0.8347
Epoch 4/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.3939 - acc: 0.9078Epoch 00004: val_loss improved from 0.56050 to 0.52043, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 276us/step - loss: 0.3958 - acc: 0.9073 - val_loss: 0.5204 - val_acc: 0.8491
Epoch 5/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.3474 - acc: 0.9214Epoch 00005: val_loss improved from 0.52043 to 0.49493, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 269us/step - loss: 0.3443 - acc: 0.9225 - val_loss: 0.4949 - val_acc: 0.8623
Epoch 6/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.3086 - acc: 0.9282Epoch 00006: val_loss improved from 0.49493 to 0.47278, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 276us/step - loss: 0.3080 - acc: 0.9284 - val_loss: 0.4728 - val_acc: 0.8539
Epoch 7/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.2775 - acc: 0.9388Epoch 00007: val_loss improved from 0.47278 to 0.47021, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 0.2763 - acc: 0.9392 - val_loss: 0.4702 - val_acc: 0.8491
Epoch 8/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.2536 - acc: 0.9451Epoch 00008: val_loss improved from 0.47021 to 0.45829, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 242us/step - loss: 0.2527 - acc: 0.9451 - val_loss: 0.4583 - val_acc: 0.8587
Epoch 9/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.2322 - acc: 0.9509Epoch 00009: val_loss improved from 0.45829 to 0.45047, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 244us/step - loss: 0.2314 - acc: 0.9512 - val_loss: 0.4505 - val_acc: 0.8539
Epoch 10/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.2131 - acc: 0.9561Epoch 00010: val_loss improved from 0.45047 to 0.44503, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 243us/step - loss: 0.2128 - acc: 0.9558 - val_loss: 0.4450 - val_acc: 0.8623
Epoch 11/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1952 - acc: 0.9628Epoch 00011: val_loss improved from 0.44503 to 0.43782, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 248us/step - loss: 0.1966 - acc: 0.9623 - val_loss: 0.4378 - val_acc: 0.8575
Epoch 12/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1818 - acc: 0.9657Epoch 00012: val_loss did not improve
6680/6680 [==============================] - 2s 245us/step - loss: 0.1819 - acc: 0.9660 - val_loss: 0.4401 - val_acc: 0.8587
Epoch 13/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1702 - acc: 0.9690Epoch 00013: val_loss improved from 0.43782 to 0.43140, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 251us/step - loss: 0.1698 - acc: 0.9690 - val_loss: 0.4314 - val_acc: 0.8647
Epoch 14/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1574 - acc: 0.9738Epoch 00014: val_loss improved from 0.43140 to 0.43137, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 249us/step - loss: 0.1577 - acc: 0.9737 - val_loss: 0.4314 - val_acc: 0.8635
Epoch 15/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1462 - acc: 0.9750Epoch 00015: val_loss improved from 0.43137 to 0.42974, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 266us/step - loss: 0.1475 - acc: 0.9744 - val_loss: 0.4297 - val_acc: 0.8563
Epoch 16/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1372 - acc: 0.9791Epoch 00016: val_loss did not improve
6680/6680 [==============================] - 2s 261us/step - loss: 0.1381 - acc: 0.9790 - val_loss: 0.4336 - val_acc: 0.8611
Epoch 17/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1301 - acc: 0.9814Epoch 00017: val_loss improved from 0.42974 to 0.42754, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 0.1302 - acc: 0.9811 - val_loss: 0.4275 - val_acc: 0.8635
Epoch 18/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1209 - acc: 0.9839Epoch 00018: val_loss improved from 0.42754 to 0.42547, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 267us/step - loss: 0.1209 - acc: 0.9838 - val_loss: 0.4255 - val_acc: 0.8659
Epoch 19/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1144 - acc: 0.9862Epoch 00019: val_loss did not improve
6680/6680 [==============================] - 2s 261us/step - loss: 0.1140 - acc: 0.9862 - val_loss: 0.4278 - val_acc: 0.8635
Epoch 20/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1070 - acc: 0.9876Epoch 00020: val_loss did not improve
6680/6680 [==============================] - 2s 260us/step - loss: 0.1075 - acc: 0.9876 - val_loss: 0.4265 - val_acc: 0.8659
Epoch 21/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.1008 - acc: 0.9891Epoch 00021: val_loss improved from 0.42547 to 0.42467, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 260us/step - loss: 0.1009 - acc: 0.9888 - val_loss: 0.4247 - val_acc: 0.8635
Epoch 22/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0954 - acc: 0.9904Epoch 00022: val_loss improved from 0.42467 to 0.42242, saving model to saved_models/weights.best.Xception.hdf5
6680/6680 [==============================] - 2s 261us/step - loss: 0.0951 - acc: 0.9903 - val_loss: 0.4224 - val_acc: 0.8659
Epoch 23/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0894 - acc: 0.9912Epoch 00023: val_loss did not improve
6680/6680 [==============================] - 2s 263us/step - loss: 0.0900 - acc: 0.9910 - val_loss: 0.4263 - val_acc: 0.8683
Epoch 24/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0850 - acc: 0.9913Epoch 00024: val_loss did not improve
6680/6680 [==============================] - 2s 268us/step - loss: 0.0855 - acc: 0.9910 - val_loss: 0.4232 - val_acc: 0.8659
Epoch 25/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0797 - acc: 0.9930Epoch 00025: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 0.0807 - acc: 0.9925 - val_loss: 0.4241 - val_acc: 0.8659
Epoch 26/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0743 - acc: 0.9940Epoch 00026: val_loss did not improve
6680/6680 [==============================] - 2s 246us/step - loss: 0.0765 - acc: 0.9933 - val_loss: 0.4227 - val_acc: 0.8683
Epoch 27/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0719 - acc: 0.9949Epoch 00027: val_loss did not improve
6680/6680 [==============================] - 2s 263us/step - loss: 0.0724 - acc: 0.9949 - val_loss: 0.4274 - val_acc: 0.8647
Epoch 28/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0689 - acc: 0.9944Epoch 00028: val_loss did not improve
6680/6680 [==============================] - 2s 276us/step - loss: 0.0683 - acc: 0.9946 - val_loss: 0.4251 - val_acc: 0.8659
Epoch 29/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0655 - acc: 0.9946Epoch 00029: val_loss did not improve
6680/6680 [==============================] - 2s 271us/step - loss: 0.0657 - acc: 0.9948 - val_loss: 0.4258 - val_acc: 0.8671
Epoch 30/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0617 - acc: 0.9953Epoch 00030: val_loss did not improve
6680/6680 [==============================] - 2s 260us/step - loss: 0.0622 - acc: 0.9952 - val_loss: 0.4255 - val_acc: 0.8671
Epoch 31/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0592 - acc: 0.9957Epoch 00031: val_loss did not improve
6680/6680 [==============================] - 2s 262us/step - loss: 0.0595 - acc: 0.9955 - val_loss: 0.4242 - val_acc: 0.8766
Epoch 32/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0571 - acc: 0.9960Epoch 00032: val_loss did not improve
6680/6680 [==============================] - 2s 262us/step - loss: 0.0567 - acc: 0.9961 - val_loss: 0.4311 - val_acc: 0.8683
Epoch 33/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0538 - acc: 0.9972Epoch 00033: val_loss did not improve
6680/6680 [==============================] - 2s 244us/step - loss: 0.0536 - acc: 0.9973 - val_loss: 0.4285 - val_acc: 0.8683
Epoch 34/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0513 - acc: 0.9958Epoch 00034: val_loss did not improve
6680/6680 [==============================] - 2s 255us/step - loss: 0.0510 - acc: 0.9960 - val_loss: 0.4289 - val_acc: 0.8659
Epoch 35/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0490 - acc: 0.9966Epoch 00035: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 0.0485 - acc: 0.9967 - val_loss: 0.4288 - val_acc: 0.8683
Epoch 36/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0465 - acc: 0.9971Epoch 00036: val_loss did not improve
6680/6680 [==============================] - 2s 253us/step - loss: 0.0465 - acc: 0.9972 - val_loss: 0.4321 - val_acc: 0.8659
Epoch 37/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0443 - acc: 0.9967Epoch 00037: val_loss did not improve
6680/6680 [==============================] - 2s 255us/step - loss: 0.0444 - acc: 0.9967 - val_loss: 0.4327 - val_acc: 0.8647
Epoch 38/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0424 - acc: 0.9974Epoch 00038: val_loss did not improve
6680/6680 [==============================] - 2s 250us/step - loss: 0.0423 - acc: 0.9975 - val_loss: 0.4329 - val_acc: 0.8611
Epoch 39/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0402 - acc: 0.9975Epoch 00039: val_loss did not improve
6680/6680 [==============================] - 2s 251us/step - loss: 0.0401 - acc: 0.9976 - val_loss: 0.4349 - val_acc: 0.8659
Epoch 40/40
6450/6680 [===========================>..] - ETA: 0s - loss: 0.0384 - acc: 0.9981Epoch 00040: val_loss did not improve
6680/6680 [==============================] - 2s 252us/step - loss: 0.0383 - acc: 0.9982 - val_loss: 0.4390 - val_acc: 0.8635
Out[10]:
<keras.callbacks.History at 0x7fafd2cc3940>
In [ ]:
# This is the second CNN I refered to in my Answer
# This second CNN is not used in my final solution

with open('saved_models/bottleneck_features_FCN_train.npy', 'rb') as features_train:
    trainsome__data = np.load(features_train)

with open('saved_models/bottleneck_features_FCN_validation.npy', 'rb') as features_validation:
    validationsome_data = np.load(features_validation)
    
with open('saved_models/bottleneck_features_FCN_test.npy', 'rb') as features_test:
    testsome_data = np.load(features_test)

Xception_modelz = Sequential()
Xception_modelz.add(Dense(133, activation='tanh', input_shape=trainsome__data.shape[1:]))
#Xception_modelz.add(Dropout(0.05))
Xception_modelz.add(Dense(133, activation='tanh'))
#Xception_modelz.add(Dropout(0.05))
#Xception_modelz.add(Dense(500, activation='relu'))
#Xception_modelz.add(Dropout(0.2))
Xception_modelz.add(Dense(133, activation='softmax'))
Xception_modelz.summary()

(IMPLEMENTATION) Load the Model with the Best Validation Loss

In [31]:
### TODO: Load the model weights with the best validation loss.
Xception_model.load_weights('saved_models/weights.best.Xception.hdf5')

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 60%.

In [32]:
### TODO: Calculate classification accuracy on the test dataset.
Xception_predictions = [np.argmax(Xception_model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_Xception]

# report test accuracy
test_accuracy = 100*np.sum(np.array(Xception_predictions)==np.argmax(test_targets, axis=1))/len(Xception_predictions)
print('Xception Test accuracy: %.4f%%' % test_accuracy)
Xception Test accuracy: 86.3636%

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.

Similar to the analogous function in Step 5, your function should have three steps:

  1. Extract the bottleneck features corresponding to the chosen CNN model.
  2. Supply the bottleneck features as input to the model to return the predicted vector. Note that the argmax of this prediction vector gives the index of the predicted dog breed.
  3. Use the dog_names array defined in Step 0 of this notebook to return the corresponding breed.

The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function

extract_{network}

where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.

In [33]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
from extract_bottleneck_features import *

def Xception_predict_breed(img_path):
    # extract bottleneck features
    bottleneck_feature = extract_Xception(path_to_tensor(img_path))
    # obtain predicted vector
    predicted_vector = Xception_model.predict(bottleneck_feature)
    # return dog breed that is predicted by the model
    return dog_names[np.argmax(predicted_vector)]

def Make_Dog_Breed_Prediction(img_path, human):
    ### If human is True, then print appropriate message for humans
    ### otherwise, print appropriate message for dogs.
    
    str = Xception_predict_breed(img_path)
    if human:
        print("If you were a dog, you'd be a: ", str[str.rfind(".") + 1:])
    else:
        print("You seem to be a: \n\t", str[str.rfind(".") + 1:])

Step 6: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [34]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.
def Detect_human(img_path):
    return (human_detector.predict(path_to_tensor(img_path)) > 0.60)
In [35]:
def dog_app(img_path):
    perform_prediction = True
    is_a_human=True
    
    if(dog_detector(img_path)):
        print("Hello, little Dog!")
        is_a_human = False
    elif(Detect_human(img_path)):
        print("Hello, human!")
    else:
        print("No interesting creature detected :(")
        perform_prediction = False
    
    img = cv2.imread(img_path)
    # get bounding box for each detected face
    #for (x,y,w,h) in faces:
        # add bounding box to color image
     #   cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
    # convert BGR image to RGB for plotting
    cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # display the image, along with bounding box
    plt.imshow(cv_rgb)
    plt.show()
    
    if(perform_prediction):
        Make_Dog_Breed_Prediction(img_path, is_a_human)

Step 7: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer:

The output is not was I was actually expecting. I expected to have a better recognition of human"s faces. My guess is that the faces used in my human's faces recognition CNN is trained very clear faces that are very well centered. The reason I am guessing so, is that even when I augmented the data on the human's faces detector CNN, it is not detecting very easily the human'faces on my photos, but it did detected very well the human's faces in the testing data set. I also noticed that when my dog's detector CNN is detecting dogs, it detected two different breeds on the same dog in two different pictures.

Points of improvement:

  • Use transfer learning to detect human's faces instead of the human"s face detector CNN used in this project. This could improve the detection of faces which are not too close as well as to detect faces in images were more than one human is present.

  • Increase the data set on the dog images by 100 to 150 percent more. This aimes to enable the CNN to learn more features of more dogs to see if it can then make better predictions of the breeds and/or to be consistent on its predictions, since it can predict different breeds on the same dog (different photos).

  • Use both, the human's face detector as well as the dog's face detector CNNs on each picture, so in case a human face is detected in the same picture where a dog is also detected, the algorithm could do both the breed prediction as well as to report the resemblance of the human's face to a dog breed.

In [36]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
test_images = load_files('/home/workspace/dog-project/my_test_Images', load_content=True)
test_images_names = np.array(test_images['filenames'])
print(test_images)
for i in test_images_names:
    dog_app(i)
    print("================================================================================")
IOPub data rate exceeded.
The notebook server will temporarily stop sending output
to the client in order to avoid crashing it.
To change this limit, set the config variable
`--NotebookApp.iopub_data_rate_limit`.

Current values:
NotebookApp.iopub_data_rate_limit=1000000.0 (bytes/sec)
NotebookApp.rate_limit_window=3.0 (secs)

Downloading data from https://github.com/fchollet/deep-learning-models/releases/download/v0.4/xception_weights_tf_dim_ordering_tf_kernels_notop.h5
83689472/83683744 [==============================] - 1s 0us/step
You seem to be a: 
	 Briard
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Alaskan_malamute
================================================================================
Hello, little Dog!
You seem to be a: 
	 Pharaoh_hound
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Anatolian_shepherd_dog
================================================================================
Hello, little Dog!
You seem to be a: 
	 Cardigan_welsh_corgi
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
Hello, human!
If you were a dog, you'd be a:  Dachshund
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Chesapeake_bay_retriever
================================================================================
Hello, little Dog!
You seem to be a: 
	 Belgian_malinois
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 American_staffordshire_terrier
================================================================================
Hello, human!
If you were a dog, you'd be a:  Beauceron
================================================================================
Hello, little Dog!
You seem to be a: 
	 Chinese_crested
================================================================================
Hello, little Dog!
You seem to be a: 
	 Beagle
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 American_eskimo_dog
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Chinese_crested
================================================================================
Hello, little Dog!
You seem to be a: 
	 Glen_of_imaal_terrier
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Havanese
================================================================================
Hello, human!
If you were a dog, you'd be a:  Chinese_crested
================================================================================
Hello, little Dog!
You seem to be a: 
	 German_pinscher
================================================================================
Hello, little Dog!
You seem to be a: 
	 Alaskan_malamute
================================================================================
Hello, human!
If you were a dog, you'd be a:  Afghan_hound
================================================================================
Hello, little Dog!
You seem to be a: 
	 American_staffordshire_terrier
================================================================================
Hello, human!
If you were a dog, you'd be a:  German_shorthaired_pointer
================================================================================
Hello, little Dog!
You seem to be a: 
	 Golden_retriever
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================
Hello, little Dog!
You seem to be a: 
	 Alaskan_malamute
================================================================================
Hello, human!
If you were a dog, you'd be a:  Border_terrier
================================================================================
Hello, little Dog!
You seem to be a: 
	 Lhasa_apso
================================================================================
No interesting creature detected :(
================================================================================
No interesting creature detected :(
================================================================================

Please download your notebook to submit

In order to submit, please do the following:

  1. Download an HTML version of the notebook to your computer using 'File: Download as...'
  2. Click on the orange Jupyter circle on the top left of the workspace.
  3. Navigate into the dog-project folder to ensure that you are using the provided dog_images, lfw, and bottleneck_features folders; this means that those folders will not appear in the dog-project folder. If they do appear because you downloaded them, delete them.
  4. While in the dog-project folder, upload the HTML version of this notebook you just downloaded. The upload button is on the top right.
  5. Navigate back to the home folder by clicking on the two dots next to the folder icon, and then open up a terminal under the 'new' tab on the top right
  6. Zip the dog-project folder with the following command in the terminal: zip -r dog-project.zip dog-project
  7. Download the zip file by clicking on the square next to it and selecting 'download'. This will be the zip file you turn in on the next node after this workspace!